<?php


namespace app\api\controller\xyb;


use addons\xyb\XypHelper;
use app\common\model\Scenic;
use app\common\model\Goods;
use app\common\model\Order as OrderModel;
use app\api\service\UsersService;
use app\common\model\marketing\MarketingCoupons;
use app\common\model\marketing\UsersMarketingCoupons;
use think\Cache;
use think\Db;

class Marketing extends Base
{
    protected $noNeedLogin = [''];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];


    /*获取用户优惠劵列表*/
    public function index()
    {
        $users = $this->getAuthUsers();
        $user_circle_id = UsersService::getUsersCircleId($users->id, 0);
        $page = $this->request->request('page', 1);
        $limit = $this->request->request('limit', 10);
        $type = $this->request->request('status', 1);
        if($circle_id = $this->request->request('circle id', 0)){
            $user_circle_id = $circle_id;
        }
        $grant_platform = $this->request->request('grant_platform', 0);
        $res = MarketingCoupons::getCouponsUsersReceiveAllLists($users->id, $user_circle_id, $type, $page, $limit, $grant_platform);
        $this->success('获取成功', $res);
    }

    /*获取可领取的优惠劵*/
    public function index_bak()
    {
        $users = $this->getAuthUsers();
        $user_circle_id = UsersService::getUsersCircleId($users->id, 0);
        $page = $this->request->request('page', 1);
        $limit = $this->request->request('limit', 10);
        $type = $this->request->request('status', 1);
        $grant_platform = $this->request->request('grant_platform', 0);
        $res = MarketingCoupons::getCouponsUsersReceiveLists($users->id, $users->circle_id, $type, $page, $limit, $grant_platform);
        $this->success('获取成功', $res);
    }

    /*用户首页优惠劵*/
    public function account_coupons()
    {
        $users = $this->getAuthUsers();
        $user_circle = UsersService::formatUsersCircleStatusInfo($users->id, $users->circle_id);

        $coupons_lists = MarketingCoupons::getCouponsUsersNotReceiveLists($users->id, $user_circle['circle_id'],  1, 5,0);
        if(count($coupons_lists['list']) < 3){
            $users_receive_lists = MarketingCoupons::getCouponsUsersReceiveLists($users->id, $users->circle_id, 2, 1, 5, 0);
            $limit = array_merge($coupons_lists['list'], $users_receive_lists['list']);
        } else {
            $limit = $coupons_lists['list'];
        }
        $limit = array_slice($limit, 0, 3);
        $this->success('获取成功', [
            'user_circle' => $user_circle,
            'coupons_lists' => ['total' => 3, 'list'=>$limit],
            'tips_mag'      => '进圈享优惠'
        ]);

        $users_receive_lists = MarketingCoupons::getCouponsUsersReceiveLists($users->id, $users->circle_id, 2, 1, 5, 0);
//        if(count($users_receive_lists['list']) > 2){
//
//        }
        /* 新用户，未加入圈子，未进入圈子*/
        if(!isset($user_circle['circle_id']) || $user_circle['circle_id'] == 0){
            $coupons_lists = MarketingCoupons::getCouponsUsersNotReceiveLists($users->id, $user_circle['circle_id'],  1, 5,0);
        } else {
            /* 未加入当前圈子; 自身有加入的圈子但未加入当前圈子 */
            if($user_circle['circle_id'] && !$user_circle['join_status']){
                $coupons_lists = MarketingCoupons::getCouponsUsersReceiveLists($users->id, $user_circle['circle_id'], 1, 1, 5, 0);
            }
            /*加入的圈子， 获取发放中，如果发放中没有，获取用户已领取的数据*/
            if($user_circle['circle_id'] && $user_circle['join_status']){
                $coupons_lists = MarketingCoupons::getCouponsUsersReceiveLists($users->id, $user_circle['circle_id'], 1, 1, 5, 0);
            }
        }

        $limit = [];

    }
    /*首页弹窗*/
    public function home_receive()
    {
        if (!$coupons_ids = $this->request->request('coupons_ids', 0)) {
            $this->error('参数错误');
        }
        $users = $this->getAuthUsers();
        $cache_key = '_home_receive_' . $coupons_ids;
        if (Cache::get($cache_key)) {
            $this->error('手慢了，优惠劵已抢光');
        }
        Cache::set($cache_key, $coupons_ids, 5);

        $user_circle = UsersService::formatUsersCircleStatusInfo($users->id, $users->circle_id);
        if(!isset($user_circle['circle_id']) || !$user_circle['circle_id']){
            $this->error('请先加入圈子');
        }
//        if (!$users_agent = UsersService::getCommunityWhereUsersLocated($users->id)) {
//            Cache::rm($cache_key);
//            $this->success('获取成功', [
//                'circle_open_stated' => false,
//            ]);
//        }
        if (!$coupons_ids = XypHelper::stringToArray($coupons_ids)) {
            Cache::rm($cache_key);
            $this->error('优惠劵不存在');
        }
        Db::startTrans();
        foreach ($coupons_ids as $val) {
            if (!$coupons = MarketingCoupons::getCouponsUsersReceiveBefore($val, $users->id, $user_circle['circle_id'])) {
                Cache::rm($cache_key);
                Db::rollback();
                $this->error('您无法领取该优惠劵');
            }
            if($coupons->receive_total >= $coupons->grant_total){
                Cache::rm($cache_key);
                Db::rollback();
                $this->error('优惠劵已抢光');
            }
//            if ($coupons->effective_date && $coupons->effective_date < time()) {
//                Cache::rm($cache_key);
//                Db::rollback();
//                $this->error('优惠劵已过期');
//            }
            $user_receive_total = UsersMarketingCoupons::getCouponsUsersReceiveTotal($users->id, $val);
            if ($user_receive_total >= $coupons->get_limit) {
                Cache::rm($cache_key);
                Db::rollback();
                $this->error('优惠劵领取已达上限');
            }
            if (!UsersMarketingCoupons::usersReceiveCoupons($users->id, $coupons)) {
                Cache::rm($cache_key);
                Db::rollback();
                $this->error('领取失败');
            }
        }
        Db::commit();
        Cache::rm($cache_key);
        $this->success('领取成功');
    }

    /*领取优惠劵*/
    public function receive()
    {
        if (!$coupons_id = (int)$this->request->request('coupons_id', 0)) {
            $this->error('参数错误');
        }
        $users = $this->getAuthUsers();
        $cache_key = 'receive_coupons_' . $coupons_id;
        if (Cache::get($cache_key)) {
            $this->error('手慢了，优惠劵已抢光');
        }
        Cache::set($cache_key, $coupons_id, 5);

        $user_circle = UsersService::formatUsersCircleStatusInfo($users->id, $users->circle_id);
        if(!isset($user_circle['circle_id']) || !$user_circle['circle_id']){
            $this->error('请先加入圈子');
        }
//        if (!$users_agent = UsersService::getCommunityWhereUsersLocated($users->id)) {
//            Cache::rm($cache_key);
//            $this->success('获取成功', [
//                'circle_open_stated' => false,
//            ]);
//        }
        if (!$coupons = MarketingCoupons::getCouponsUsersReceiveBefore($coupons_id, $users->id, $user_circle['circle_id'])) {
            Cache::rm($cache_key);
            $this->error('优惠劵不存在');
        }
        if($coupons->receive_total >= $coupons->grant_total){
            Cache::rm($cache_key);
            Db::rollback();
            $this->error('优惠劵已抢光');
        }
        if ($coupons->receive_start_time > time()) {
            Cache::rm($cache_key);
            $this->error('优惠劵未到领取时间');
        }
        if ($coupons->receive_end_time < time()) {
            Cache::rm($cache_key);
            $this->error('优惠劵已过期');
        }
        $user_receive_total = UsersMarketingCoupons::getCouponsUsersReceiveTotal($users->id, $coupons_id);
        if ($user_receive_total >= $coupons->get_limit) {
            Cache::rm($cache_key);
            $this->error('优惠劵领取已达上限');
        }
        if (!UsersMarketingCoupons::usersReceiveCoupons($users->id, $coupons)) {
            Cache::rm($cache_key);
            $this->error('领取失败');
        }
        Cache::rm($cache_key);
        $this->success('领取成功', [
            'use_system_product' => MarketingCoupons::usingSystemProducts($coupons)
        ]);
    }

    /*获取用户可使用的优惠劵*/
    public function get_usable_coupons()
    {
        $users = $this->getAuthUsers();
        $circle_id = UsersService::getUsersCircleId($users->id, $users->circle_id);
        /*使用平台：1跑腿；2：商城*/
        $grant_platform = $this->request->request('grant_platform', 1);
        /*1:跑腿；2：帮我取*/
        $errand_method = $this->request->request('errand_method', 0);
        /*商家ID*/
        $business_id = $this->request->request('ticket_business_id', 0);
        /*产品ID*/
        $product_id = $this->request->request('ticket_product_id', 0);
        /*金额*/
        $amount = $this->request->request('amount', 0);
        /*是否显示随机立减金额*/
        $is_show_amount = $this->request->request('is_show_amount', false);

        $lists = UsersMarketingCoupons::getUsersUsableCoupons($users->id, $amount, $grant_platform, $errand_method, $business_id, $product_id, $is_show_amount);
        $this->success('获取成功', $lists);
    }

    /*获取用户产品优惠劵*/
    public function get_users_product_coupons()
    {
        $users = $this->getAuthUsers();
        $user_circle = UsersService::formatUsersCircleStatusInfo($users->id, $users->circle_id);

        /*商家ID*/
        $business_id = $this->request->request('ticket_business_id', 0);
        /*产品ID*/
        $product_id = $this->request->request('ticket_product_id', 0);

        /*是否显示随机立减金额*/
        $is_show_amount = $this->request->request('is_show_amount', false);

        $lists = MarketingCoupons::getUsersProductReceiveCoupons($users->id, 3, $business_id, $product_id, $user_circle['circle_id']);
        if(!$lists){
            $this->success('获取成功', ['title' => '', 'lists' => [], 'max_amount' => 0]);
        }
        $max_amount = 0;
        $last_max_amount = '';
        $tips_items = [];
        foreach ($lists as $k=>$v){
            $coupons_amount_tips = $v['coupons_amount_tips'];
            $tips_items[$coupons_amount_tips['discount']] = $coupons_amount_tips['tips'];
            if($coupons_amount_tips['discount'] && $coupons_amount_tips['discount'] > $max_amount){
                $max_amount = $coupons_amount_tips['discount'];
                $last_max_amount = $coupons_amount_tips['tips'];
            } else {
                $last_max_amount = $coupons_amount_tips['tips'];
            }
        }
        krsort($tips_items);

        $this->success('获取成功', [
            'title'      => '领取'.count($lists).'张商家优惠劵，'.$last_max_amount,
            'lists'      => $lists,
            'max_amount' => $max_amount,
            'tags_lists' => array_values($tips_items)
        ]);
    }

    /*领取商家优惠劵*/
    public function get_usable_business()
    {
        $users = $this->getAuthUsers();
        if(!$coupon_id = $this->request->request('coupons_id', 0)){
            $this->error(__('Invalid parameters'));
        }
        if(! $marketing_coupons = MarketingCoupons::where('id', $coupon_id)->find()){
            $this->error(__('Invalid parameters'));
        }
        if($marketing_coupons['grant_platform'] != 3){
            $this->error(__('Invalid parameters'));
        }
        $business_ids =  $product_ids = [];
        $product_lists_map = [];
        if($marketing_coupons['grant_ticket_method'] == 2){
            $business_ids = XypHelper::stringToArray($marketing_coupons['grant_ticket_business_id']);
        }else{
            $product_ids = XypHelper::stringToArray($marketing_coupons['grant_ticket_product_id']);
        }
        if(!$business_ids && !$product_ids){
            $this->error(__('Invalid parameters'));
        }
        if($product_ids){
            $where = ['id' => ['in', $product_ids]];
            $product_lists = Goods::field('id,goods_name,scenic_id')->where($where)->select();

            foreach ($product_lists as $val){
                $product_lists_map[$val['scenic_id']][] = $val;
            }
            $business_ids = array_keys($product_lists_map);
        }

        $scenicModel = new Scenic();
        if ($this->auth->isLogin()) {
            $shop_id = $this->auth->is_distributor == 1 ? $this->auth->id : $this->auth->shop_id;
        }else{
            $shop_id = 2;
        }
        //景区信息
        $where = ['id' => ['in', $business_ids], 'status' => 1];
        $scenicModel->setShopId($shop_id);
        $field = ['id','scenic_name','scenic_images','city','address','total_sales','score','category_id'];
        //$scenic = $scenicModel->getScenicList($where,$field,$page);
        $scenic = $scenicModel->getScenicList($where,$field);

        if ($this->auth->isLogin() && $scenic && $this->auth->is_distributor) {
            switch ($this->auth->level) {
                case '1':
                    $share_price = 'one_price';
                    break;
                case '2':
                    $share_price = 'two_price';
                    break;
                case '3':
                    $share_price = 'three_price';
                    break;
            }
            $allocationModel = new \app\common\model\DistributionAllocation();
            foreach ($scenic as &$value) {
                $allocation = $allocationModel->field($share_price)->where(['scenic_id'=>$value['id']])->order($share_price.' desc')->find();
                $value['share_price'] = $allocation[$share_price];
                //景区商品价格信息
                $salesModel = new \app\store\model\Sales();
                $listSales = $salesModel->field('scenic_id,salePrice,retailPrice')->where(['scenic_id'=>$value['id'],'sales_status'=>1])->select();
                $listSales = collection($listSales)->toArray();
                $value['prices'] = $listSales;
                $value['products'] = isset($product_lists_map[$value['id']])?$product_lists_map[$value['id']]:[];
            }
        }else{
            foreach ($scenic as &$value) {
                $allocationModel = new \app\common\model\DistributionAllocation();
                $allocation = $allocationModel
                    ->field('subtract,subtract_money,num_restriction,total_restriction,goods_id')
                    ->where(['scenic_id'=>$value['id'],'subtract'=>2])->order('subtract_money desc')->find();
                $value['subtract_money'] = $allocation['subtract_money'];
                //判断用户是否登录，如果登录，获取当前用户限购商品的订单数量，与限购数量进行比较
                $value['num_restriction']   = $allocation['num_restriction'];
                $value['total_restriction'] = $allocation['total_restriction'];
                $value['discounts_number']  = $allocation['num_restriction'];
                $orderModel = new OrderModel();
                if($this->auth->isLogin() && $allocation && !$this->auth->is_distributor) {
                    $userTicketNum = $orderModel->ticketNumNew($this->auth->id,$allocation['goods_id']);
                    if($allocation['num_restriction'] <= $userTicketNum) {
                        $value['discounts_number'] = 0;
                    }
                }
                //没有限购张数限制
                if($value['num_restriction'] == 0) {
                    $value['discounts_number'] = -1;
                }
                //有总票数限制
                $totalTicketNum = $orderModel->ticketNumNew(0,$allocation['goods_id']);
                if($totalTicketNum >= $value['total_restriction']) {
                    $value['discounts_number'] = 0;
                }
                //景区商品价格信息
                $salesModel = new \app\store\model\Sales();
                $listSales = $salesModel->field('scenic_id,salePrice,retailPrice')->where(['scenic_id'=>$value['id'],'sales_status'=>1])->select();
                $listSales = collection($listSales)->toArray();
                $value['prices'] = $listSales;
                $value['products'] = isset($product_lists_map[$value['id']])?$product_lists_map[$value['id']]:[];
            }
        }
        $data['scenic'] = $scenic;
        $data['coupons'] = MarketingCoupons::getCouponsDetails($coupon_id, (isset($users->id)?$users->id:0));
        if ($this->auth->isLogin()) {
            $data['is_distributor'] = $this->auth->is_distributor;
        }else{
            $data['is_distributor'] = 0;
        }
        $this->success('动态关联多个景区信息', $data);
    }

    /*获取优惠劵分类*/
    public function get_coupons_category(){
        $this->success('动态关联多个景区信息', [
            [
                'label'     => '全部',
                'value'     => 0,
                'icon'      => '',
            ],
            [
                'label'     => '互助',
                'value'     => 2,
                'icon'      => 'https://api.youdaike.com/static/index-header2/huzhu.png',
            ],
            [
                'label'     => '商城',
                'value'     => 3,
                'icon'      => 'https://api.youdaike.com/static/daijia/coupons/Frame@2x(1).png',
            ],
        ]);
    }
}

